$(function() {
    // refreshBtn
    var root = $('#root');
    var serialEl = $('[name=serial]', root);
    var bitrateEl = $('[name=bitrate]', root);
    var parityBitEl = $('[name=parityBit]', root);
    var stopBitsEl = $('[name=stopBits]', root);
    var sendHexEl = $('[name=sendHex]', root);
    var refreshBtn = $('.refreshBtn', root);
    var connectBtn = $('.connectBtn', root);
    var sendBtn = $('.sendBtn', root);
    var cancelBtn = $('.cancelBtn', root);
    var disconnectBtn = $('.disconnectBtn', root);
    var messageEl = $('.message', root);
    var logEl = $('.log', root);

    var openedSerials = {};
    var openedSerialIds = {};

    refreshBtn.click(function() {
        refreshSerialList();
    });


    Serial.addListener(function(info) {
        console.log(Serial.buffer2Array(info.data));
        writeLog(openedSerialIds[info.connectionId], '<span style="color:green;">接收</span>', Serial.buffer2HexStr(info.data));
    });

    function writeLog(com, type, log) {
        var message = logEl.html();
        if (message) {
            message += '<br />';
        }
        message += dateFormat(new Date(), 'hh:mm:ss') + ' ';
        message += com;
        message += ': [' + type + '] ';
        message += log.replace(/ /g, '&nbsp;');
        logEl.html(message);
        logEl.scrollTop(logEl[0].scrollHeight);  
    }


    connectBtn.click(function() {
        var serial = serialEl.val();
        Serial.connect(serial, {
            bitrate : parseInt(bitrateEl.val()),
            parityBit : parityBitEl.val(),
            stopBits : stopBitsEl.val()
        }).done(function(info) {
            openedSerials[serial] = info;
            openedSerialIds[info.connectionId] = serial;
            successMessage('打开串口成功!');
        }).fail(function() {
            errorMessage('打开串口失败! 请检查指定串口是否存在或已被打开! ');
        });
    });

    cancelBtn.click(function() {
        logEl.html('');
    });

    disconnectBtn.click(function() {
        var serial = serialEl.val();
        if (!openedSerials[serial]) {
            waringMessage('串口尚未打开!');
            return;
        }
        var connectionId = openedSerials[serial].connectionId;
        Serial.disconnect(connectionId, {
            bitrate : parseInt(bitrateEl.val()),
            parityBit : parityBitEl.val(),
            stopBits : stopBitsEl.val()
        }).done(function() {
            delete openedSerialIds[connectionId];
            delete openedSerials[serial];
            successMessage('关闭串口成功!');
        }).fail(function() {
            errorMessage('关闭串口失败! ');
        });
    });

    sendBtn.click(function() {
        var hexStr = sendHexEl.val();
        var serial = serialEl.val();
        if (!openedSerials[serial]) {
            errorMessage('串口尚未打开!');
            return;
        }
        writeLog(serial, '<span style="color:red;">发送</span>', hexStr + ' 发送中... ');
        Serial.sendHexStr(openedSerials[serial].connectionId, hexStr.replace(/ /g, '')).done(function() {
            successMessage('发送数据成功!');
            writeLog(serial, '<span style="color:red;">发送</span>', hexStr + ' 成功! ');
            console.log(arguments);
        }).fail(function() {
            writeLog(serial, '<span style="color:red;">发送</span>', hexStr + ' 失败! ');
            errorMessage('发送数据失败!');
            errorMessage(arguments);
        });
    });

    refreshSerialList();
    
    function refreshSerialList() {
        Serial.getDevices().done(function(portsArray) {
            serialEl.empty();
            for (var i = 0; i < portsArray.length; i++) {
                serialEl.append('<option value="' + portsArray[i].path + '">' + portsArray[i].path + '</option>');
            }
        });
    }

    function successMessage(msg) {
        messageEl.html('<span style="color:green;">' + msg + '</span>');
    }

    function errorMessage(msg) {
        messageEl.html('<span style="color:red;">' + msg + '</span>');
    }

    function waringMessage(msg) {
        messageEl.html('<span style="color:orange;">' + msg + '</span>');
    }


    function dateFormat(date, fmt) {
        var o = {
            "M+": date.getMonth() + 1, //月份 
            "d+": date.getDate(), //日 
            "h+": date.getHours(), //小时 
            "m+": date.getMinutes(), //分 
            "s+": date.getSeconds(), //秒 
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
            "S": date.getMilliseconds() //毫秒 
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        
        return fmt;
    }
});